/************************************************************
** Eric Koeppen
** CS 235
** Final Project
** Description:   file_IO.c
**
************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include "./studentList.h"


#define BUFFER_SIZE 1024

char buf[BUFFER_SIZE];

/************************************************************
** function:      fwriteGrades
************************************************************/
void fwriteGrades(FILE *fpt, gradeType* g) {
gradeType *temp = g;
gradeType *check = g;

	if(temp->ident >= 0) {
	  check = getNextGrade(check);
	  while (check) {
	  		fprintf(fpt, "%s,%d,%5.2f,", temp->name, temp->classification, temp->grade);
			temp = getNextGrade(temp);
	  		check = getNextGrade(check);
		}
		fprintf(fpt, "%s,%d,%5.2f", temp->name, temp->classification, temp->grade);
	} else {
	  printf("No Grades\n");
	}
}

/*************************************************************************
* void parseCSV( char *filename )
Read one line at a time from filename. Make a new student from the first
three columns of data and then parse the line for each student grade,
adding the grade to the grade list list.  After reading all grades, assign the 
grade list to the student.

Read all lines until EOF.

The code is based on the pattern of 
student, grade, grade, grade, etc, end of line
student = ident (integer), first name (string), last name (string)
grade = grade name (string), grade classification (integer), grade (float),
        generated ident (integer)

 ************************************************************************/

void parseCSV( char *filename ) {

	//printf("parse 1 filename: %s\n",filename);
	//sleep(5);
	FILE * pInput;
	char * tok;
	int    studentIdent;
	int    gradeIdent;
	int    myInt;
	float  myFloat;
   studentType *tempStdPT1;
   gradeType   tempGrd;
   studentType tempStd = nullStudent();
   gradebookType currentBook;

	printf("parse 2 filename: %s\n",filename);

	if ((pInput = fopen(filename, "r")) == NULL) {
		printf("Unable to open: %s  to read the grades.  Try a different file\n\n");
		return;
	}

	//pInput = fopen(filename, "r");
   /******************* read in the master template *****************************/
   fgets(buf, sizeof(buf), pInput);
   tok = strtok(buf, ",");
   strcpy(tempStd.firstname, tok);                          // First Name String 
   tok = strtok(NULL, ",");
   strcpy(tempStd.lastname, tok);                           // First Name String 
   currentBook.master = initStudentList(tempStd);
   while (NULL != (tok = strtok(NULL, ","))) {              // loop to read one grade for current student
      strcpy(tempGrd.name, tok);                            // Grade Name String 
      tok = strtok(NULL, ",");
      tempGrd.classification = atoi(tok);                   // Grade Classification
      tok = strtok(NULL, ",");
      tempGrd.grade = atof(tok);		                        // Grade to float
      addGrade(tempGrd, currentBook.master->studentGrades); // Add the grade to the gradelist
   }
      	printf("parse 3 filename: %s\n",filename);
   /******************* read in the students *****************************/
	while (fgets(buf, sizeof(buf), pInput) != NULL) {  // Read in a line of the CSV file
      tok = strtok(buf, ",");
      strcpy(tempStd.firstname, tok);                 // First Name String 
      tok = strtok(NULL, ",");
      strcpy(tempStd.lastname, tok);                  // First Name String
      tempStd.studentGrades = initGradeList();		   // Initialize the grade list for the new student
      addStudent(tempStd);	                           // Add the new student to the student list
	printf("parse 4 filename: %s\n",filename);
      while (NULL != (tok = strtok(NULL, ","))) {     // loop to read one grade for current student
         strcpy(tempGrd.name, tok);                   // Grade Name String 
			tok = strtok(NULL, ",");
         tempGrd.classification = atoi(tok);          // Grade Classification
			tok = strtok(NULL, ",");
         tempGrd.grade = atof(tok);		               // Grade to float
			tempGrd.ident = gradeIdent++;                // Assign then Increment gradeIdent
			addGrade(tempGrd, tempStd.studentGrades);    // Add the grade to the gradelist
		}
	}
		printf("parse 5 filename: %s\n",filename);
	fclose(pInput);
}

/*************************************************************************
* void writeCSV( char *filename )

Write all students and grades to the file.

The code is based on the pattern of 
student, grade, grade, grade, etc, end of line
student =  first name (string), last name (string)
grade = grade name (string), grade classification (integer), grade (float),

 ************************************************************************/

void writeCSV( char *filename ) {

	FILE * pOutput;
	char * tok;
	int    gradeIdent;
	int    myInt;
	float  myFloat;
    studentType *tempStdPT1;

    if ((pOutput = fopen(filename, "w")) == NULL) {
		printf("Unable to open: %s  to write the grades.\n\n", filename);
        return;
	}

	tempStdPT1 = getMaster();
	fprintf(pOutput, "%s,", tempStdPT1->firstname);
	fprintf(pOutput, "%s,", tempStdPT1->lastname);
    fwriteGrades(pOutput, tempStdPT1->studentGrades);
		fprintf(pOutput, "\n");
	tempStdPT1 = getFirstStudent();
	while (tempStdPT1 != NULL) {   // get the first student
		fprintf(pOutput, "%s,", tempStdPT1->firstname);
		fprintf(pOutput, "%s,", tempStdPT1->lastname);
	    fwriteGrades(pOutput, tempStdPT1->studentGrades);
		fprintf(pOutput, "\n");
	    tempStdPT1 = getNextStudent(tempStdPT1);
	}
	printf("\nFile has been saved!\n");
	fclose (pOutput);
}

/************************************************************
** function:      loadGradeBooks
**	descripton:		This will read the database directory to see
**						if any gradebooks already exist and allow the
**						user to select one for edit/display.
************************************************************/
int loadGradeBooks()
{
	//printf("entering loadGradebook\n");
	int				i = 0;
	DIR				*dp;
   struct dirent	*dnp;
   char				gbArray[40][30];
   
   if ((dp = opendir("./databases")) == NULL)
   {
   	perror("opendir");
   	return 0;
   }
	// The directory is open, now read the files in it
	while ((dnp = readdir(dp)) != NULL)
	{
		if (dnp->d_name[0] != '.')  // ignore files that begin with a period
		{
			// add to the gradebook array
			strcpy(gbArray[i],dnp->d_name);
			i++;
		}       
	}
	closedir(dp);
	//printf("Sending: %s %s %s\n",gbArray[0],gbArray[1],gbArray[2]);
	gradebookListMenu(i,gbArray);
}

